
	// a variable to keep track of whether the voting ajax is already running
	var voting = 0;
	var registering_reaction = 0;
	var change_type_stat_running = 0;


function addlistenersvote()
{
	// for the voting thing
$(function () {
	$('.voteup,.votedown').hover(
		function() {
		$(this).addClass('votehover');
		},
	    function() {
	    	$(this).removeClass('votehover');
	    } 
	);
    $('.voteup,.votedown').click(function() {
				
		if($(this).hasClass('voteselect')) 
		{ 
			//show_msg('vote_msg',"hide");
			//show_msg('<span class="vote_msg">Can vote only once.</span>',"alert"); 
			return; 
		}
		
		
		var id = $(this).attr('id');
		var user = $('#loggedin_userid').text();
		// if already some voting is being done, the fuck off
		if(voting == 1) return;
		else voting = 1;
		
		var temp = new Array();
		temp = id.split("_");
		var action = temp[0];
		
		var baseid; // of the entity to be voted 		
		// incrementing the id		
		if(action == "voteup")
		{
			baseid = id.substr(7);
			var counter_id = "votecount_"+baseid;
			$('#'+counter_id+'').text(parseInt($('#'+counter_id+'').text())+1);
			if($('#votedown_'+baseid).hasClass('voteselect'))
				$('#votedown_'+baseid).removeClass('voteselect').addClass('votearrow');
			else 
				$('#voteup_'+baseid).addClass('voteselect').removeClass('votearrow');
		}
		else if(action == "votedown")
		{
			baseid = id.substr(9);
			var counter_id = "votecount_"+baseid;
			$('#'+counter_id+'').text(parseInt($('#'+counter_id+'').text())-1);
			if($('#voteup_'+baseid).hasClass('voteselect'))
				$('#voteup_'+baseid).removeClass('voteselect').addClass('votearrow');
			else 
				$('#votedown_'+baseid).addClass('voteselect').removeClass('votearrow');
		}
		
		
		$.ajax({
			type: "POST",
			url: "php/ajax/post/register_vote.php",
			data: "baseid="+baseid+"&user="+user+"&action="+action,
			success: function(msg) {
					if(msg == "success")
					{
						// do nothing for now
					}
					else // something went wrong 
					{
					if(msg == "again")
						//show_msg('<span class="vote_msg">Can vote only once.</span>',"alert");
						
						if(temp[0] == "voteup")
						$('#'+counter_id+'').text(parseInt($('#'+counter_id+'').text())-1);
						else if(temp[0] == "votedown")
						$('#'+counter_id+'').text(parseInt($('#'+counter_id+'').text())+1); 
					}   	
					voting = 0;
					}
		});
		 
	});	
});

}


function open_comment(ele)
{
	var id = $(ele).attr('id');
		id = id.substr(8);
		if($('#commentbox_'+id+'').is(":visible"))
			$('#commentbox_'+id+'').slideUp();
		else
		 	{
		 		$('.commentbox').slideUp();
		 		$('#commentbox_'+id+'').slideDown('slow', function() {
		 			$(this).find('input[type=text]').focus();
		 		})		 		
		 	}
}

function submit_commentbox(user, element, type)
{
	var val = $('#post_box_' + type + '').val();
	if(val == "") {
		$('#postbox_err_msg_' + type + '').text('Its empty, girl!');
		return;
	}
	if(val.length > 400) {
		$('#postbox_err_msg_' + type + '').text('Too long! 400 characters only.');
		return;
	}
	$('#postbox_err_msg_' + type + '').text('');
	$(element).attr('disabled', true).css('opacity','0.5').val("Saving");
	var postas = $('#postbox_postas_' + type + '').val();
		
		$.ajax({ 
				type : "POST",
				url : "php/ajax/commentbox_submit.php",
				data : "user=" + user + "&val=" + val + "&postas=" + postas + "&type=" + type,
				success : function(msg) {
					
					var temp = new Array();
					temp = msg.split("_");
					if(temp[0] != "id")
						{ show_msg(msg, "perm"); return; }
					else
						var postid = temp[1];						 
							
					$(element).attr('disabled', false).css('opacity','0.8').val("Post");
					$('#post_box_' + type + '').val("");
					//$('#'+type+'').slideUp();
		
					//alerting the OP about the new comment
					init_subscription(postid, "comment");
					// we wont initiate the online stat function
					// just the init_comments funciton, we don't put that much load on the server
					
					init_comments(user,type);					
		
				}
			});
}

function init_comments(user,type, offset)
{
		//this function is called in two cases:
		//1. first time to invoke the main thread
		//2. to invoke earlier thread, in which case the offset parameter is se 
		
	if(typeof offset === 'undefined')
		var params = "user="+user+"&type="+type;
	else
		{
		var params = "user="+user+"&type="+type+"&offset="+offset;
		$('#'+type+'_more').removeClass('a').removeClass('stream_more').html('<img src="images/21.gif" />');
		}
	//show_msg("fetching stream", "perm" );
	$.ajax({
			type: "POST",
			url: "php/ajax/stream/fetch_comments.php", 
			data: params,
			success: function(data){
				
					var json = eval('('+data+')')
					var output = json['output'];
					var error = json['error'];
					var postid = json['postid'];
						
					var arr = new Array();
					arr = type.split("_");
					if(arr[0] == "new" && output!="")
					{
					
						$('#'+type+'').replaceWith(output);
						//shimmer_new();
					}
					else if(arr[0]!="new")
					{
				
						if(error!="") { show_msg(error, "perm"); return; }
						else
						{
							if(typeof offset === 'undefined'){
							$('#comments_stream_post_'+postid+'').html(output);
							//shimmer_new();					
							}
							else{
								$('#'+type+'_more').replaceWith('<div class="shimmer_new" style="display:none">'+output+'</div>');
								shimmer_new();
							}
						}
					}								
				}
			});
}
function init_subscription(postid, type,async1)
{
	//show_msg("sending","perm");
	//alert(type);
	if(async1 === undefined)
	 async1 = "true";
	 
	if(async1 == "true")
	 async2 = true;
	 else
	 async2 = false;
	   
	$.ajax({
		type: "POST",
		url: "php/ajax/stream/init_subscribe.php",
		async: async2,
		data: "id="+postid+"&type="+type,
		success: function(msg) {
			//if(msg!="") alert(msg);
			//if(msg!="") alert("back_"+msg);	
		}
	});
	//show_msg("sent","perm");
}



// to be corrected
function init_stream(user, type, offset)
{
	//show_msg("fetching stream","perm");	
	if(typeof offset === 'undefined')
		var params = "user="+user+"&type="+type;
	else
		{
		var params = "user="+user+"&type="+type+"&offset="+offset;
		$('#'+type+'_more').removeClass('a').removeClass('stream_more').html('<center><img src="images/22.gif" /></center>');
		}
	
	var temp = new Array(); 
	temp = type.split("_");			
	
	//if(temp[0] == "new")
		//$('#'+type+'').html('<center><span class="small-font faded">fetching new stuff</span></center>');
				
	//show_msg("fetching stream", "perm" );
	$.ajax({
			type: "POST",
			url: "php/ajax/fetch_stream.php",
			data: params,
			success: function(msg){
				
				if(temp[0] == "new" && msg=="")
						$('#'+type+'').html('');
		
				if(temp[0] == "new" && msg!="")
				{
					$('#'+type+'').replaceWith('<div class="shimmer_new" style="display:none">'+msg+'</div>');					
					shimmer_new();
					//
						//alert("here");
						//alert($('#pb_wrapper_wrapper').offset().top);
					//if(just_posted == 1)
					//{
						$('html, body').animate({
							scrollTop: ($('#pb_wrapper_wrapper').offset().top)
						}, 'slow');					 
					//}
					fix_pb();
				}
				else 
				{
				if(typeof offset === 'undefined')
					{ 
						$('#stream_'+type+'').html(msg); 				
						$('html, body').animate({
							scrollTop: ($('#stream_'+type).offset().top + $('#stream_'+type).height())
						}, 'slow');					 
					} 
				else
					{	
						$('#'+type+'_more').replaceWith('<div class="shimmer_new" style="display:none">'+msg+'</div>');						
						shimmer_new(); 						
						//$('#stream_'+type).scrollTop($('#stream_'+type).height());							
						}
						fix_pb();
				}
			
			}
			});		 
}

function init_pms(user, type, offset)
{
		//this function is called in three cases:
		//1. first time to invoke the main thread
		//2. to invoke earlier thread, in which case the offset parameter is set
		//3. to invoke new threads, from polling, in which case the type is modified. 
		
		//show_msg("fetching stream","perm");
		//stop the online process for the time being	
		
	//show_msg(offset+'<br>', "perm");
	
	if(typeof offset === 'undefined')
		var params = "user="+user+"&type="+type;
	else
		{
		var params = "user="+user+"&type="+type+"&offset="+offset;
		$('#'+type+'_more').removeClass('a').removeClass('stream_more').html('<center><img src="images/22.gif" /></center>');
		}
	//show_msg("fetching stream", "perm" );
	$.ajax({
			type: "POST",
			url: "php/ajax/pms/fetch_pms.php",
			data: params,
			success: function(data){
				var json = eval('('+data+')')
				var msg = json['output'];
				var timestamp = json['timestamp'];
				
				// addding or replacing
				// the output message
				var temp = new Array();
				var type1;
				temp = type.split("_");
				if(temp[0] == "poll")
				{
					type1 = ""+temp[1]+"_"+temp[2]+"_"+temp[3]+"";
					$('#stream_'+type1+'').append(msg);
					
					$('html,body').animate({
    						scrollTop: $('#post_box_'+type1).offset().top},
    						'slow');				
				}
				// else its either previous msgs or main stream 
				else{
					type1 = type; //// that way type1 will have the actual string
					if(typeof offset === 'undefined') 
						{
							$('#stream_'+type+'').html(msg);	
							$('html,body').animate({
    						scrollTop: $('#post_box_'+type1).offset().top},
    						'slow');						
						}  
					else
						{
							$('#'+type+'_more').replaceWith('<div class="shimmer_new" style="display:none">'+msg+'');
							shimmer_new();
						}
				}
								
				
					
				clearTimeout(online_stat_time);	
				online_stat();
				
				// starting polling again only when offset is not set
				if(typeof offset === 'undefined' || temp[0] == "poll")
					init_polling(user, type1, timestamp);	
			}
			});	
}

function register_reaction(reaction, user, postid, element)
{
	//show_msg("saving..","perm");
	if(registering_reaction != 0) return; else registering_reaction = 1;
	var id = $(element).attr('id');
	var original_val = $('#'+id+'_count').text();
	if(original_val == "") original_val = 0;
	
	show_msg('<span class="register_reaction_msg">saving</span>',"perm");
	$.ajax({
		type: "POST",
		url: "php/ajax/post/save_reaction.php",
		data: "reaction="+reaction+"&user="+user+"&postid="+postid,
		success: function(msg){
			registering_reaction = 0;
			show_msg('register_reaction_msg',"hide");
			if(msg=="success")
			{
					$('#'+id+'_count').text(parseInt(original_val)+1).addClass('reaction_count');
					$('#'+id+'').addClass('user-reaction');
			}
			else if(msg=="del")
			{
				if((parseInt(original_val) -1) == 0)
					$('#'+id+'_count').text("").removeClass('reaction_count');
				else
					$('#'+id+'_count').text(parseInt(original_val) -1).removeClass('reaction_count');
					$('#'+id+'').removeClass("user-reaction");				
			}
			else if(msg == "change")
			{
				$(element).parent().parent().find('.reaction').each(function() {
					if($(this).hasClass('user-reaction'))
						{
							var pid = $(this).attr('id');
							var in_value = parseInt($('#'+pid+'_count').text());
							if(in_value =="") in_value = 0;
							
							if(in_value-1 <= 0) in_value="";
							else in_value = in_value-1;
							$('#'+pid+'_count').text(in_value);
							if(in_value=="") $('#'+pid+'_count').removeClass('reaction_count');
							$(this).removeClass('user-reaction');
						}
				});
				$('#'+id+'_count').text(parseInt(original_val)+1).addClass('reaction_count');
				$('#'+id+'').addClass('user-reaction');
			}
			else 	
			{
			//$('#'+id+'_count').val(parseInt(original_val)-1);
			show_msg('<span class="add_reaction_msg">something went wrong</span>',"alert");
			}
			//show_msg("","hide");		
			//init_stream(user,'post_'+postid);
			
		}
		});	
}

function subscribe_group(user, gpid, action, ele)
{
	$(ele).replaceWith('processing');

	$.ajax({
		type: "POST",
		url: "php/ajax/group/subscribe.php",
		data: "user="+user+"&gpid="+gpid+"&action="+action,
		success: function(msg){
			if(msg!="") 
				show_msg('<span class="gpsub_msg">'+msg+'</span>', "alert");
			else 
				{
					if(action == "subscribe")
						$('span.group_subscribe').html('<span class="a" onclick=\'subscribe_group('+user+', '+gpid+', "unsubscribe", this)\'>Unsubscribe</span>');
					else if(action == "unsubscribe")
						$('span.group_subscribe').html('<span class="a" onclick=\'subscribe_group('+user+', '+gpid+', "subscribe", this)\'>Subscribe </span>');			

				}
			}
		});	
}


function init_inbox(user, fbid)
{

	//show_msg('<span class="inbox_err">refereshing</span>',"perm");
	$.ajax({
		type: "POST",
		url: "php/ajax/pms/fetch_inbox.php",
		data: "user="+user+"&fbid="+fbid,
		success: function (msg) {
			//show_msg("inbox_err","hide");
			$('#user_conversations').html(msg);	
		} 		
	});
}

function init_polling(user, type, timestamp)
{ 
	show_msg("poll_err","hide");
	//alert(timestamp);
	var status = $('#curr_type_stat_u').val();
	
	jxhr = $.ajax({
		type: "POST",
		url: "php/ajax/pms/poll.php", 
		async: true,
		data: "user="+user+"&type="+type+"&timestamp="+timestamp+"&status="+status,
		success: function(data) {
			var json = eval('('+data+')');
			if(json['output'] != "") alert(json['output']);
			 
			if(json['status']!="")  
				$('#curr_type_stat_u').val(json['status']);
			
			if(json['status'] == "typing")
			 $('#type_stat_wrapper').text("user is typing..");
			else if(json['status'] == "static" || json['status'] == "")
			$('#type_stat_wrapper').text("");
			
					
			if(json["new"] == "true")
				 init_pms(user, "poll_"+type+"", timestamp);
			else 
				setTimeout(
                    'init_polling("'+user+'", "'+type+'", "'+timestamp+'")', /* Try again after.. */
                    "1000"); /* milliseconds (5seconds) */
			
		},
		 error: function(XMLHttpRequest, textStatus, errorThrown){
		 		//if(textStatus!="")
               //show_msg('<span class="poll_err">chat error: '+textStatus+' <span class="a" onclick=\'window.location.reload();\'>refresh</span><br></span>',"perm");
                setTimeout(
                    'init_polling("'+user+'", "'+type+'", "'+timestamp+'")', /* Try again after.. */
                    "5000"); /* milliseconds (5seconds) */
            },
		 
	});
}
 
function shimmer_new()
{
	$('.shimmer_new').slideDown(200, function() {
		var inside = $(this).html();
		$(this).replaceWith(inside);		
	});	
}

function type_stat(type, user)
{ 
	var val = $('#post_box_'+type).val();
	
	if(val != "" && $('#curr_type_stat').val()!="typing")  {
		$('#curr_type_stat').val("typing");
		change_type_stat(type, user);
		}
	else if(val == "" && $('#curr_type_stat').val() != "static"){
		$('#curr_type_stat').val("static");
		change_type_stat(type, user);
		}
		
}
function change_type_stat(type, user)  
	{	
		
		if (change_type_stat_running == 0) change_type_stat_running = 1;
		else return; 
	
		var status = $('#curr_type_stat').val();
		
		$.ajax({
			type: "POST",
			url: "php/ajax/pms/save_type_stat.php",
			data: {"user":user, "type": type, "status": status },
			success: function (msg) {
				change_type_stat_running = 0;
				//show_msg("inbox_err","hide");
				//$('#user_conversations').html(msg);			
				if(msg!="") alert(msg);
			} 		
		});
	}	
	 
function refresh_unread()
{
	$('#user_unread_header').text("refreshing unread..");
	var user = $('#loggedin_userid').text();
	$.ajax({
			type: "POST",
			url: "php/ajax/pms/user_unread.php",
			data: {"user":user},
			success: function (msg) {
				$('#user_unread_header').html(msg);
			} 		
		});
}


